package visualizer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.jdom.JDOMException;

import tracer.StreamRedirectThread;


public class Visualize {

	//Christian: fileCounterMap speichert zu jeder "orderID-Anzahl"(managed orderID) einen Chronologischen Counterwert 
	private HashMap<String, Integer> fileCounterMap = new HashMap<String, Integer>();
	
	// Thread transferring remote error stream to our error stream
	private Thread errThread = null;
	// Thread transferring remote output stream to our output stream
	private Thread outThread = null;
	
	private String graphVizCommand;
	
	public Visualize(String graphVizCommand) {
		this.graphVizCommand = graphVizCommand;
	}
		
	public int start(String id, String workDir) {
		HashMap<String, List<Node>> nodes = new HashMap<String, List<Node>>();

		int counter = 0;
		
		try {
			File dir = new File(workDir);
			for(File file: dir.listFiles()) {
				String filename = file.getName();
				if(filename.startsWith("kovida_") && filename.endsWith(".xml")) {
					String managedOrderId = filename.substring(filename.indexOf("-")+1, filename.indexOf("."));
					int fileCounter = Integer.valueOf(filename.substring(filename.indexOf("_")+1,filename.indexOf("_"+id)));
					// hier den fileCounter zur managedOrderID abspeichern
					fileCounterMap.put(managedOrderId, fileCounter);
					nodes.put(managedOrderId, ObjectParser.getObjects(file.toURI().toASCIIString()));
				}
			}
			// aus nodes einen graph erzeugen nodes beinhaltet zu jeder orderID eine Liste von Nodes
			LayeredGraph graph = new LayeredGraph(nodes);
			// aus dem Graphen Dotfiles erzeugen
			HashMap<String, String> files = graph.generateDotfiles();
			Iterator<String> it = files.keySet().iterator();
			while(it.hasNext()) {
				String managedOrderId = (String)it.next();
				String fileName = "kovida_"+fileCounterMap.get(managedOrderId)+"_"+id+"-"+managedOrderId;
				FileWriter writer = new FileWriter(workDir+"/"+fileName+".dot");
				writer.write(files.get(managedOrderId));
				writer.close();
				runGraphViz(fileName, workDir);
				counter++;
				System.out.println("runGraphViz: "+counter +" von "+files.size());
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return counter;
	}
	
	public void runGraphViz(String filename, String workDir) {
		try
        {            
            Runtime rt = Runtime.getRuntime();
            String[] cmd = {graphVizCommand,"-Tgif", "-o"+filename+".gif", filename+".dot"};
            File dir = new File(workDir);
            Process proc = rt.exec(cmd, null, dir);
            redirectOutput(proc);
            proc.waitFor();

    		try {
    		    errThread.join(); // Make sure output is forwarded 
    		    outThread.join(); // before we exit
    		} catch (InterruptedException exc) {
    		    // we don't interrupt
    		}
        } 
        catch (Throwable t) {
            t.printStackTrace();
        }
	}
	
    void redirectOutput(Process process) {
        // Copy target's output and error to our output and error.
        errThread = new StreamRedirectThread("error reader", process.getErrorStream(), System.err);
        outThread = new StreamRedirectThread("output reader", process.getInputStream(), System.out);
        errThread.start();
        outThread.start();
    }

}
